package com.nuanshui.heatedloan.fund.biz.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.OrderNumGenerate;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.AccountBillBizType;
import com.nuanshui.heatedloan.constant.FreezeFundState;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dubbo.DubboResponse;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.JadeCurrencyMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserAccountBillMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserFundActionMapper;
import com.nuanshui.heatedloan.fund.enums.PlatformEnum;
import com.nuanshui.heatedloan.fund.facade.JadeCurrencyService;
import com.nuanshui.heatedloan.fund.form.UseJadeCurrencyForm;
import com.nuanshui.heatedloan.fund.model.JadeCurrencyUse;
import com.nuanshui.heatedloan.fund.model.JadeMoneyRule;
import com.nuanshui.heatedloan.fund.model.SystemCurrency;
import com.nuanshui.heatedloan.fund.model.UserAccountBill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(readOnly=true,value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
public class JadeCurrencyServiceImpl extends CommonServiceImpl implements JadeCurrencyService {

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private OrderNumGenerate orderNumGenerate;

	@Autowired
	private JadeCurrencyMapper jadeCurrencyMapper;
	@Autowired
	private UserFundActionMapper userFundActionMapper;
	@Autowired
	private UserAccountBillMapper userAccountBillMapper;
	
	private static final Logger logger = LoggerFactory.getLogger("jadeCurrency");
	
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public SystemCurrency jadeCurrencyOrder(Integer price, Integer type,String userId)
	{
		
		if(price!=null && type!=null)
		{
			String dealNum = orderNumGenerate.getDealNum(AccountBillBizType.JADE_CURRENCY);//交易号
			//获取玉币的奖励的规则
			List<JadeMoneyRule> list = jadeCurrencyMapper.selectJadeMoneyRule();
			int size = list.size();
			Integer jadeValue=0;//奖励的玉币数额
			String ruleId = null;//用于保村JadeMoneyRule的id
			for (int i =size-1;i>=0;i--)
			{
				JadeMoneyRule sty = list.get(i);
				long min = sty.getMinValue()*100;
				long max = sty.getMaxValue()*100;
				if(price>=min && price<=max)
				{
					ruleId=sty.getId();
					//用户充值玉璧已经送过了，每个规则充值第一次送玉币
					if(jadeCurrencyMapper.selectJadeCurrencyUserIdRuleId(userId, ruleId)>0)
					{
						ruleId=null;
						break;
					}
					else
					{
						
						jadeValue=sty.getJadeMoneyValue();
						break;
					}
				}
			}
			LogUtil.info(logger, "取出的系统玉币数面值是："+jadeValue);
			
			SystemCurrency sc = new SystemCurrency();
			sc.setDealNum(dealNum);
			sc.setPrice(price.longValue());
			sc.setTotalPrice((price.longValue()+jadeValue.longValue()*100));
			sc.setUserId(userId);
			sc.setStatus(0);
			sc.setType(type);
			sc.setCreatedAt(new Date());
			sc.setRuleId(ruleId);
			//生成支付玉币的账单
			jadeCurrencyMapper.saveSystemCurrency(sc);
			LogUtil.info(logger, "生成支付玉币的账单成功~！");
			return sc;
		}
		else
		{
			LogUtil.info(logger, "订单参数错误!");
			error("参数错误！");
		}
		return null;
	}
	
	/**
	 * 获取玉币充值规则
	 */
	@Override
	public List<JadeMoneyRule> jadeCurrencyRechargeRule()
	{
		List<JadeMoneyRule> list = jadeCurrencyMapper.selectJadeMoneyRule();
		return list;
	}

	@Override
	public Long loadTotalJadeCurrency(String userId) {

		return jadeCurrencyMapper.loadTotalJadeCurrency(userId);
	}

	//@Override
	//@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	/*public boolean rechargeJadeCurrency(PayForm payForm) {
		LogUtil.info(logger, "玉币支付订单号>>>>>>>>>>"+payForm.getOrderNum());
		String orderNum = payForm.getOrderNum();
		long price = payForm.getPayPrice().longValue();//支付的金钱
		
		SystemCurrency sc= jadeCurrencyMapper.selectSystemCurrency(orderNum);
		if(sc!=null && sc.getStatus()!=null && sc.getStatus()==0)//校验支付状态0表示未支付  同是也防止支付宝三个月后进行回调
		{
			if(sc!=null && sc.getPrice()!=null && sc.getPrice()==price)//校验支付的金额是否正确
			{
				//修改玉币订单的状态
				jadeCurrencyMapper.updateSystemCurrency(orderNum, sc.getTotalPrice()!=null ? sc.getTotalPrice() : 0);
				Date date=new Date();
				//添加充值玉币的明细情况
				jadeCurrencyMapper.saveSystemCurrencyDetail(orderNum, price, 1, date);//实际支付金额
				jadeCurrencyMapper.saveSystemCurrencyDetail(orderNum, (sc.getTotalPrice()-price), 2, date);//平台奖励的玉币数
				//添加入账记录
				jadeCurrencyMapper.insertBillRecord(price*-1,sc.getUserId(),AccountBillType.JADECURRENCY_TYPE,AccountBillStatus.COMPLETE,payForm.getPayType(),orderNum,AccountBillName.JADECURRENCY_NAME,sc.getId(),null,null,null);
			    
				if(PayType.YE.equals(payForm.getPayType()))  {
					UserFundAction ufa = new UserFundAction();
					ufa.setMoney(price*-1);
					ufa.setActionType(FundActionType.JADE_CURRENCY);
					ufa.setUserId(sc.getUserId());
					ufa.setStatus(FundActionState.COMPLETE);
					ufa.setPlatform(PayType.YE);
					ufa.setDealNum(payForm.getOrderNum());
					userFundActionMapper.saveUserFundAction(ufa);
				}
			
			}
			else
			{
				LogUtil.info(logger, "玉币支付金额核对有误！");
				error("玉币支付金额核对有误！");
			}
		}
		else
		{
			LogUtil.info(logger, "玉币订单支付状态有误！");
			error("玉币支付金额核对有误！");
		}
		return false;
	}*/

	/**
	 * 确认使用的玉币
	 * @Param billId 如果billId 不为空表示账单已经生成，只更新状态，如果为空表示账单还未生成，则 生成账单
	 * 
	 */
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public DubboResponse confirmUseJadeCurrency(UseJadeCurrencyForm form) {
        DubboResponse response = new DubboResponse();
		if(SysStringUtils.isEmpty(form.getOrderNum())) return response;
		String billId = form.getBillId();
		//使用玉币
		JadeCurrencyUse use = jadeCurrencyMapper.selectJadeCurrencyUsc(form.getOrderNum());
		if(use!=null)
		{
			jadeCurrencyMapper.updateSystemCurrencyUscStutus(form.getOrderNum());
		}else {
			use = new JadeCurrencyUse();
		}

		if(SysStringUtils.isNotEmpty(billId)) {//不为空则只更新账单的玉币使用
			userAccountBillMapper.updateUseJadeCurrency(billId, use.getPrice());
		}else {//为空则生成账单
			String dealNum = orderNumGenerate.getDealNum(form.getBillBizType());
			UserAccountBill userAccountBill = new UserAccountBill();
			userAccountBill.setUserId(form.getUserId());
			userAccountBill.setDealNum(dealNum);
			userAccountBill.setMoney(form.getUserPrice());
			userAccountBill.setName(form.getTitle());
			userAccountBill.setStatus(FreezeFundState.COMPLETE);
			//userAccountBill.setType(form.getBillType());
			userAccountBill.setBizId(form.getBizId());
			userAccountBill.setJadeCurrency(use.getPrice());
			userAccountBill.setPlatform(form.getPlatform());
			userAccountBill.setSubType(form.getSubBillType());
			userAccountBillMapper.insertBillRecord(userAccountBill);
			response.setData(dealNum);
		}
		//生成账单
		return response;
	}

	@Override
	public JadeCurrencyUse selectJadeCurrencyUsc(String orderNum) {
	
		return jadeCurrencyMapper.selectJadeCurrencyUsc(orderNum);
	}

	@Override
	public SystemCurrency selectSystemCurrency(String dealNum) {
		
		return jadeCurrencyMapper.selectSystemCurrency(dealNum);
	}

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void updateSystemCurrencyUscStutus(String dealNum) {
		JadeCurrencyUse use = jadeCurrencyMapper.selectJadeCurrencyUsc(dealNum);
		if(use!=null)
		{
			jadeCurrencyMapper.updateSystemCurrencyUscStutus(dealNum);
		}
		
	}
	/**
	 * 退还玉币使用
	 * @param @param dealNum
	 * @author guohao
	 * @date 2016年7月22日 下午4:28:20
	 * @since $
	 */
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void refundSystemCurrencyUsc(String dealNum) {
		JadeCurrencyUse use = jadeCurrencyMapper.selectJadeCurrencyUsc(dealNum);
		if(use!=null)
		{
			jadeCurrencyMapper.refundSystemCurrencyUsc(dealNum);
		}
		
	}

	/**
	 * 增加用户虚拟币
	 */
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public DubboResponse addUserCurrency(Long price,String userId,String billTitle) {
		DubboResponse response = new DubboResponse();
		if(price!=null)
		{
			String dealNum = orderNumGenerate.getDealNum(AccountBillBizType.GIVE_JADE_CURRENCY);//交易号
			//添加虚拟币			
			SystemCurrency sc = new SystemCurrency();
			sc.setDealNum(dealNum);
			sc.setPrice(price);
			sc.setTotalPrice(price);
			sc.setUserId(userId);
			sc.setStatus(FreezeFundState.COMPLETE);
			sc.setType(0);
			sc.setCreatedAt(new Date());
			//生成支付玉币的账单
			jadeCurrencyMapper.saveSystemCurrency(sc);
			//添加虚拟拟币明细
			jadeCurrencyMapper.saveSystemCurrencyDetail(dealNum,price, 2,new Date());//平台奖励的玉币数
			//生成添加的账单
			UserAccountBill userAccountBill = new UserAccountBill();
			userAccountBill.setUserId(userId);
			userAccountBill.setDealNum(dealNum);
			userAccountBill.setMoney(0l);
			userAccountBill.setName(billTitle);
			userAccountBill.setStatus(FreezeFundState.COMPLETE);
			//userAccountBill.setType(AccountBillType.GIVE_JADE_CURRENCY);
			userAccountBill.setPlatform(PlatformEnum.PLATFORM_SYS.getName());
			userAccountBill.setBizId(sc.getId());
			userAccountBillMapper.insertBillRecord(userAccountBill);		
		}
		
		
		return response;
	}

	
}
